import React, { PureComponent } from 'react';
import { Modal, Form, Select, Input, Upload, message, Icon, Button, DatePicker, Radio, Row, Col } from 'antd';
import styles from '../../../components/common/PateoTable/TableList.less';
import moment from 'moment';

const styleRequired = {
  display: 'inline-block',
  marginRight: '4px',
  content: '*',
  fontFamily: 'SimSun',
  lineHeight: '1',
  fontSize: '14px',
  color: '#f5222d',
};
const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;
const RadioGroup  = Radio.Group;
// @Form.create()
export default class BindUserModal extends PureComponent {
  state = {
    data: [],
    buttonLoading: false,
    fullFaceUrlList: [],
    backViewUrlList: [],
    handPhotoUrlList: [],
    bindData: {},
  };
  componentWillReceiveProps(nextProps) {
    const { bindData } = nextProps;
    if (bindData.sid !== this.state.bindData.sid) {
      this.setState({ bindData });
    }
 };
  getLabel = (lable) => <span><span style={styleRequired}>* </span>{lable}</span>;
  setIcon = (urls) => {
    this.setState({
      icon: urls,
    });
  };
  ok = (e) => {
    e.preventDefault();
    const { form, handleClose, dispatch } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState({
        buttonLoading: true,
      });
      const obj = fieldsValue;
      /**
       *userName
       * mobilePhone
       *certificateType
       * certificateNumber
       * address
       * time
       * url    this.state.icon
       * frontIDUrl
       * backIdUrl
       * holdIdUrl
       * leaseStartTime
       * leaseExpirationTime
       *
       */
      obj.frontIDUrl=this.state.fullFaceUrlList[0].response.url;
      obj.backIdUrl=this.state.backViewUrlList[0].response.url;
      obj.holdIdUrl=this.state.handPhotoUrlList[0].response.url;
      obj.vin=this.state.bindData.vin;
      obj.groupId = this.state.bindData.groupId;
      obj.leaseStartTime= `${moment(fieldsValue.time[0]).format('YYYY-MM-DD HH:mm')}`;
      obj.leaseExpirationTime=`${moment(fieldsValue.time[1]).format('YYYY-MM-DD HH:mm')}`;
      obj.time=null;
      dispatch({
        type: 'bestForm/add',
        payload: { url: '/groupManagement/bingUser', ...obj },
        callback: (response) => {
          if (response) {
            response.statusCode === '0' ? message.success('提交绑定申请成功') : message.error("提交绑定申请失败");
            this.setState({
              fullFaceUrlList: [],
              backViewUrlList: [],
              handPhotoUrlList: [],
              buttonLoading: false,
            });
            form.resetFields();
            handleClose();
          }
          this.props.dispatch({
            type: 'vehicle/fetch',
            payload: {
              page: 0,
              size: 10,
            }})
        },
      });
    });
  };
  checkFullFaceUrl = (rule, value, callback) => {
    const { fullFaceUrlList } = this.state;
    if (fullFaceUrlList.length === 0) {
      callback('请上传身份证正面照');
      return;
    }
    callback();
  };
  checkBackViewUrl = (rule, value, callback) => {
    const { backViewUrlList } = this.state;
    if (backViewUrlList.length === 0) {
      callback('请上传身份证背面照');
      return;
    }
    callback();
  };
  checkHandPhotoUrl = (rule, value, callback) => {
    const { handPhotoUrlList } = this.state;
    if (handPhotoUrlList.length === 0 ) {
      callback('请上传身份证手持照');
      return;
    }
    callback();
  };
  handleFullFaceUrlChange = (info) => {
    let { fileList } = info;
    fileList = fileList.slice(-1);
    if (info.file.status === 'done' && info.file.response && info.file.response.error === 0) {
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    } else if (!info.file.status) {
      this.setState({
        fullFaceUrlList: [],
      });
      return;
    }
    this.setState({ fullFaceUrlList: fileList });
  };
  handleBackViewUrlChange = (info) => {
    let { fileList } = info;
    fileList = fileList.slice(-1);
    if (info.file.status === 'done' && info.file.response && info.file.response.error === 0) {
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    } else if (!info.file.status) {
      this.setState({
        backViewUrlList: [],
      });
      return;
    }
    this.setState({ backViewUrlList: fileList });
  };
  handleHandPhotoUrlChange = (info) => {
    let { fileList } = info;
    fileList = fileList.slice(-1);
    if (info.file.status === 'done' && info.file.response && info.file.response.error === 0) {
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    } else if (!info.file.status) {
      this.setState({
        handPhotoUrlList: [],
      });
      return;
    }
    this.setState({ handPhotoUrlList: fileList });
  };
  close = () => {
    const { handleClose, form } = this.props;
    this.setState({
      icon: null,
      buttonLoading: false,
      fullFaceUrlList: [],
      backViewUrlList: [],
      handPhotoUrlList:[]
    });
    form.resetFields();
    handleClose();
  };
  handleCancel = () => this.setState({ previewVisible: false })
  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };
  beforeUpload = (file) => {
    if (file.type === 'image/jpeg' || file.type === 'image/png') {
      if (file.size / 1024 / 1024 > 5) {
        message.error('图片大小不能大于5MB!');
        return false;
      }
      return true;
    } else {
      message.error('请上传JPG或PNG格式图片！');
      return false;
    }
  };
  renderSimpleForm() {
    const { previewVisible, previewImage,
      buttonLoading } = this.state;
    const domain = window.g.url;
    const url = '/common/picupload';
    const str = `${domain}${url}`;
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传图片</div>
      </div>
    );
    const { visible } = this.props;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 16 },
      },
    };
    return (
      <div>
        <Modal
          title="绑定用户"
          width={600}
          visible={visible}
          onCancel={this.close}
          footer={[
            <Button key="back" size="default" onClick={this.close}>
              取消
            </Button>,
            <Button loading={buttonLoading} key="save" type="primary" size="default" onClick={this.ok}>
              保存
            </Button>,
          ]}
        >
          <Form>
            <FormItem
              {...formItemLayout}
              label="用户姓名"
            >
              {getFieldDecorator('userName', {
                rules: [
                  { required: true, message: '请输入用户姓名',whitespace: true}
                ],
              })(
                  <Input  maxLength="6"/>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label='性别'
            >
              {getFieldDecorator('sex', {
                rules: [
                  { required: true, message: '请选择性别' },
                ],
              })(
                <RadioGroup>
                  <Radio value="0">男</Radio>
                  <Radio value="1">女</Radio>
                </RadioGroup>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="手机号码"
            >
              {getFieldDecorator('mobilePhone', {
                rules: [{ required: true, message: '手机号码有误', whitespace: true, pattern: /^1[0-9][0-9]\d{8}$/ }],
              })(
                <Input placeholder="请填写手机号码" />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="证件类型"
            >
              {getFieldDecorator('certificateType', {
                rules: [
                  { required: true, message: '请选择证件类型' },
                ],
              })(
                <Select placeholder="请选择证件类型">
                  <Option key="1">居民身份证</Option>
                  <Option key="2">护照</Option>
                  <Option key="3">军官证</Option>
                  <Option key="4">警官证</Option>
                  <Option key="5">统一社会信用代码</Option>
                  <Option key="6">港澳居民来往内地通行证</Option>
                  <Option key="7">台湾居民来往大陆通行证</Option>
                  <Option key="8">其它</Option>
                </Select>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="证件号码"
            >
              {getFieldDecorator('certificateNumber', {
                rules: [
                  { required: true, message: '请填写证件号码',whitespace: true },
                ],
              })(
                <Input maxLength="30" placeholder="请填写证件号码" />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="地址"
            >
              {getFieldDecorator('address', {
                rules: [
                  { required: true, message: '请填写地址', whitespace: true },
                ],
              })(
                <Input maxLength="30" placeholder="请填写地址" />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="租赁时间"
            >
              {getFieldDecorator('time', {
                rules: [
                  { required: true, message: '请选择租赁时间' },
                ],
              })(
                <RangePicker
                  showTime
                  format="YYYY-MM-DD HH:mm"
                  placeholder={['开始时间', '结束时间']}
                  disabledDate={current => current && (current) < moment().endOf('day')}
                  //onChange={onChange}
                  //onOk={onOk}
                />
              )}
            </FormItem>
            <Row  gutter={24}>
              <Col lg={6} md={12} sm={24} offset={4}>
                <FormItem
                  label={this.getLabel('身份证正面照')}
                >
                  {getFieldDecorator('frontIDUrl', {
                    rules: [{ validator: this.checkFullFaceUrl }],
                  })(
                    <Upload
                      action={str}
                      accept=".png, .gif, .jpeg, .jpg, .bmp"
                      listType="picture-card"
                      fileList={this.state.fullFaceUrlList}
                      onPreview={this.handlePreview}
                      onChange={this.handleFullFaceUrlChange}
                      beforeUpload={this.beforeUpload}
                    >
                      {this.state.fullFaceUrlList.length >= 1 ? null : uploadButton}
                    </Upload>
                  )}
                </FormItem>
              </Col>
              <Col lg={6} md={12} sm={24}>
                <FormItem
                  label={this.getLabel('身份证背面照')}
                >
                  {getFieldDecorator('backIdUrl', {
                    rules: [{ validator: this.checkBackViewUrl }],
                  })(
                    <Upload
                      action={str}
                      accept=".png, .gif, .jpeg, .jpg, .bmp"
                      listType="picture-card"
                      fileList={this.state.backViewUrlList}
                      onPreview={this.handlePreview}
                      onChange={this.handleBackViewUrlChange}
                      beforeUpload={this.beforeUpload}
                    >
                      {this.state.backViewUrlList.length >= 1 ? null : uploadButton}
                    </Upload>
                  )}
                </FormItem>
              </Col>
              <Col lg={6} md={12} sm={24}>
                <FormItem
                  label={this.getLabel('身份证手持照')}
                >
                  {getFieldDecorator('holdIdUrl', {
                    rules: [{ validator: this.checkHandPhotoUrl }],
                  })(
                    <Upload
                      action={str}
                      accept=".png, .gif, .jpeg, .jpg, .bmp"
                      listType="picture-card"
                      fileList={this.state.handPhotoUrlList}
                      onPreview={this.handlePreview}
                      onChange={this.handleHandPhotoUrlChange}
                      beforeUpload={this.beforeUpload}
                    >
                      {this.state.handPhotoUrlList.length >= 1 ? null : uploadButton}
                    </Upload>
                  )}
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Modal>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    );
  }


  renderForm() {
    return this.renderSimpleForm();
  }
  render() {
    return (
      <div className={styles.tableListForm}>
        {this.renderForm()}
      </div>
    );
  }
}
